// Package main implements a server for Greeter service.
package main

import (
	"context"
	"fmt"
	"io"
	"log"
	"math/rand"
	"net"
	"os"
	"os/signal"
	"syscall"
	"time"

	"google.golang.org/grpc"

	pb "gitee.com/aoliang/graceful/quick_close_grpc/proto"
)

const (
	port = ":50051"
)

// server is used to implement helloworld.GreeterServer.
type server struct{}

// SayHello implements helloworld.GreeterServer
func (s *server) SayHello(ctx context.Context, in *pb.HelloRequest) (*pb.HelloReply, error) {
	time.Sleep(10 * time.Second)
	time.Sleep(time.Duration(rand.Intn(10)+5) * time.Millisecond)
	return &pb.HelloReply{Message: "Hello " + in.Name}, nil
}

func (s *server) SayStreamHello(stream pb.Greeter_SayStreamHelloServer) error {
	for {
		in, err := stream.Recv()
		if err == io.EOF {
			return nil
		}
		if err != nil {
			return err
		}

		l := rand.Intn(3) + 1
		for i := 0; i < l; i++ {
			if err := stream.Send(&pb.HelloReply{Message: fmt.Sprintf("hello %s", in.Name)}); err != nil {
				return err
			}
		}
	}
}

func main() {
	fmt.Println("pid:", os.Getpid())

	lis, err := net.Listen("tcp", port)
	if err != nil {
		log.Fatalf("failed to listen: %v", err)
	}
	s := grpc.NewServer()
	pb.RegisterGreeterServer(s, &server{})

	go func() {
		if err := s.Serve(lis); err != nil {
			log.Fatalf("failed to serve: %v", err)
		}
	}()
	ch := make(chan os.Signal, 1)
	signal.Notify(ch, syscall.SIGTERM, syscall.SIGINT, syscall.SIGKILL)
	<-ch
	fmt.Println("receive stop signal")
	s.Stop()
}
